package praktikumid.w10.p4;

import java.awt.Graphics;
import java.awt.Point;
import java.awt.event.MouseEvent;

public class Rectangle extends Shape {

	private Point start;
	private int width = 0;
	private int height = 0;
	
	@Override
	public void paintComponent(Graphics g) {
		super.paintComponent(g);
		if (start != null) {
			int left = Math.min(start.x, start.x + width);
			int up = Math.min(start.y, start.y + height);
			g.drawRect(left, up, Math.abs(width), Math.abs(height));
		}
	}
	
	@Override
	public void mouseDragged(MouseEvent e) {
		if (start == null) {
			start = e.getPoint();
		} else {
			width = e.getPoint().x - start.x;
			height = e.getPoint().y - start.y;
		}
	}
	
	@Override
	public void mouseReleased(MouseEvent e) {
		if (start != null) {
			isFinished = true;
		}
	}
	
	@Override
	public void mouseClicked(MouseEvent e) {
		start = e.getPoint();
		isFinished = true;
	}
	
	@Override
	public int getDistance(Point p) {
		// TODO: doesn't work well
		int d = Math.abs(p.x - start.x);
		d = Math.min(d, Math.abs(p.x - start.x + width));
		d = Math.min(d, Math.abs(p.y - start.y));
		d = Math.min(d, Math.abs(p.y - start.y + height));
		return d;
	}
	
	@Override
	public void move(int dx, int dy) {
		if (start != null) {
			start.x = start.x + dx;
			start.y = start.y + dy;
		}
	}

}
